package com.fecean.aabbc.netty.service;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import lombok.extern.slf4j.Slf4j;

import java.io.Serializable;
import java.time.Instant;
import java.util.HashMap;
import java.util.Map;

/**
 * * ICE响应对象
 *
 * @blame Android Team
 */
@Slf4j
public class IceResponse implements Serializable {

    private static final long serialVersionUID = -15566392376959798L;

    private String cmd;

    private String uuid;

    private int status = 0;

    private String msg = "成功";

    @JsonProperty("current_database_datetime")
    private long currentDataBaseDatetime;

    private Map<String, Object> data = new HashMap<>();

    public IceResponse(String cmd, String uuid) {
        this.cmd = cmd;
        this.uuid = uuid;
        currentDataBaseDatetime = Instant.now().toEpochMilli();
    }

    public IceResponse() {
        currentDataBaseDatetime = Instant.now().toEpochMilli();
    }

    public int getStatus() {
        return status;
    }

    public void setStatus(int status) {
        this.status = status;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public Map<String, Object> getData() {
        return data;
    }

    public String getCmd() {
        return cmd;
    }

    public String getUuid() {
        return uuid;
    }

    public long getCurrentDataBaseDatetime() {
        return currentDataBaseDatetime;
    }

    public void setCurrentDataBaseDatetime(long currentDataBaseDatetime) {
        this.currentDataBaseDatetime = currentDataBaseDatetime;
    }

    public String toJson(){
        try{
            ObjectMapper mapper = new ObjectMapper();
            return mapper.writeValueAsString(this);
        }
        catch(Exception ex){
            ObjectMapper mapper = new ObjectMapper();
            ObjectNode root = mapper.createObjectNode();
            root.put("cmd", this.cmd);
            root.put("uuid", this.uuid);
            root.put("status", -1);
            root.put("current_database_datetime", this.currentDataBaseDatetime);
            root.put("msg", ex.toString());
            try {
                return mapper.writeValueAsString(root);
            } catch (JsonProcessingException e) {
                log.error("", e);
                throw new RuntimeException(e);
            }
        }
    }
}
